<template>
  <div class="app-container pending-tasks" v-spin-loading="isLoadingToDo">
    <div class="pending-tasks_header">
      <div class="pending-tasks_total">
        <CustomTitle title="待办任务" />
        <div v-if="unAssignedInfo.num" class="unassgin-total" @click="toUnassignList">
          {{ unAssignedInfo.num }}个{{ unAssignedInfo.type == 1 ? "营销" : "工程" }}客户待分配
        </div>
      </div>
      <div class="pending-tasks_filter">
        <div class="custom-tabs">
          <div
            :class="{ 'custom-tabs_item-active': item.value == timePeriod.type }"
            v-for="item in timeRange"
            :key="item.label"
            @click="changeTime(item.value)"
          >
            {{ item.label }}
          </div>
        </div>
        <a-range-picker
          style="width: 250px"
          v-if="timePeriod.type == 'custom'"
          v-model="timePeriod.timeRange"
          @change="setCustomTime as any"
        />
      </div>
    </div>
    <div class="pending-tasks_state">
      <a-radio-group v-model="params.status" @change="changeTasksState as any">
        <a-radio value="all">全部({{ numbers.allNumber || 0 }})</a-radio>
        <a-radio value="not_start">未开始({{ numbers.notStartNumber || 0 }})</a-radio>
        <a-radio value="ing">跟进中({{ numbers.ingNumber || 0 }})</a-radio>
        <a-radio value="audit">审核中({{ numbers.auditNumber || 0 }})</a-radio>
        <a-radio value="refuse">未通过({{ numbers.failNumber || 0 }})</a-radio>
        <a-radio value="complete">已完成({{ numbers.completedNumber || 0 }})</a-radio>
        <a-radio value="normal">正常({{ numbers.normalNumber || 0 }})</a-radio>
        <a-radio value="not_complete" class="overdue">超期未完成({{ numbers.notCompleteNumber || 0 }})</a-radio>
        <a-radio value="postpone_not_start" class="overdue">超期未开始({{ numbers.postponeNotStartNumber || 0 }}) </a-radio>
      </a-radio-group>
    </div>
    <div class="pending-tasks_self">
      <a-checkbox-group :default-value="[true]">
        <template v-for="item in [true]">
          <a-checkbox :value="item">
            <template #checkbox="{ checked }">
              <a-space align="center" :class="{ 'custom-checkbox-card-checked': checked }" @click="handleCheckMyTask(checked)">
                <div className="custom-checkbox-card-mask">
                  <div className="custom-checkbox-card-mask-dot" />
                </div>
                <div>
                  <div className="custom-checkbox-card-title">只看我的任务</div>
                </div>
              </a-space>
            </template>
          </a-checkbox>
        </template>
      </a-checkbox-group>
      <a-input-group>
        <a-select
          v-model="params.searchType"
          :options="[
            { label: '客户', value: 2 },
            { label: '负责人', value: 1 }
          ]"
          :style="{ width: '100px' }"
          @change="init"
        />
        <a-input v-model="params.value" :style="{ width: '160px' }" placeholder="请输入" @blur="init" @keyup.enter="init" />
      </a-input-group>
    </div>
    <a-table :data="toDoTable" :columns="columns as any" :pagination="false" :stripe="true" :scroll="{ x: '130%', y: '100%' }">
      <template #customerName="{ record }">
        <span class="customer-link" @click="toCustomerInfo(record.customerId)">{{ record.customerName }}</span>
      </template>
      <template #operate="{ record }">
        <!--   1  流程任务  2 跟进延期任务  -->
        <!--        <div v-if="record.isOperate && ['not_start', 'ing'].includes(record.taskStatus)"-->
        <div v-if="['not_start', 'ing'].includes(record.taskStatus)" style="display: flex; align-items: center">
          <a-button
            v-if="record.taskType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK"
            type="text"
            size="mini"
            @click="handelOpenProcessDrawer(record)"
            >待办</a-button
          >
          <a-button
            v-if="record.taskType === defaultConfig.taskTypeObj.PROCESS_TASK"
            type="text"
            size="mini"
            @click="handelOpenDrawer(record)"
            >待办</a-button
          >
          <a-button
            v-if="['not_start', 'ing'].includes(record.taskStatus)"
            type="text"
            @click="handleAdjustTime(record)"
            size="mini"
            >调整计划</a-button
          >
        </div>
        <template v-if="record.isOperate && record.taskStatus == 'complete'">
          <a-button type="text" size="mini" @click="handelCheckDetail(record, true)">编辑</a-button>
        </template>
        <template v-if="record.taskStatus == 'complete'">
          <a-button type="text" size="mini" @click="handelCheckDetail(record, false)">查看</a-button>
        </template>
        <a-button v-show="record.formInstanceId" @click="handelAudit(record)" type="text" size="mini">审批</a-button>
      </template>
    </a-table>
    <a-pagination
      :total="total"
      v-model:current="params.current"
      v-model:page-size="params.size"
      show-total
      show-jumper
      show-page-size
      @change="handleChangePagination"
      @page-size-change="handleChangeSizePagination"
    />
  </div>

  <!--
  TODO:弹窗封装
  流程任务待办 start -->
  <a-drawer
    :width="1000"
    :visible="isHandelDrawer"
    :header="false"
    :footer="false"
    unmountOnClose
    @close="handelCloseProcessDrawer"
  >
    <div class="handel-container" v-if="isHandelDrawer">
      <div class="form-container">
        <custom-title :title="drawerTaskName" />
        <!--      start  操作说明 -->
        <div class="opt-instructions" ref="instructionsTitle">
          <icon-question-circle />
          <span @click="openInstructions">操作说明</span>
        </div>
        <!--      end  操作说明 -->

        <!--     start 任务表单   -->
        <div class="form-items" v-spin-loading="isLoadingForm">
          <micro-app
            class="micro-app"
            name="form-design-todo"
            :url="appUrlConfig.formDesign"
            baseroute="/form-design"
            default-page="/home"
            fiber
            :data="{ token: getToken() }"
            router-mode="native"
            @mounted="flowMounted"
            @error="flowError"
          />
        </div>
        <!--      end  任务表单  -->

        <!--start 下一个任务-->
        <div class="next-task" v-spin-loading="isLoadingNextTask" v-if="isShowNextTask && nextTaskList.length">
          <div class="next-task-title">下个任务</div>
          <a-form label-align="left" auto-label-width>
            <a-form-item v-for="item in nextTaskList" :label="item.taskName">
              <a-date-picker :disabled-date="disabledDate" v-model="item.plainStartDate" :disabled="isCheckDetail" />
            </a-form-item>
          </a-form>
        </div>
        <!--end 下一个任务-->

        <div class="form-btns">
          <a-button style="width: 92px; background-color: #f2f3f5" type="secondary" @click="handelCloseProcessDrawer"
            >取消</a-button
          >
          <a-button
            style="width: 92px"
            type="primary"
            v-if="!isCheckDetail && customerInfoParam.currentType === 1"
            :disabled="isUploadFile && isGetUploadFileUrl"
            @click="handelSubmitFormItem"
            >确定</a-button
          >
        </div>
      </div>
      <!--    start  跟进  -->
      <div class="followUp-container">
        <div class="followUp-top">
          <div class="custom-tabs">
            <div
              :class="{ 'custom-tabs_item-active': referFollowTabIndex === item.value }"
              v-for="item in referFollowTabs"
              :key="item.value"
              @click="changeCustomTab(item)"
            >
              {{ item.label }}
            </div>
          </div>
          <icon-close @click="handelCloseProcessDrawer" />
        </div>
        <div class="followUp-logs" v-if="referFollowTabIndex == 0" v-spin-loading="isLoadingFollow">
          <follow-timeline :follow-up-data="followUpData" :is-check-detail="isCheckDetail" @add-follow="handelOpenAddFollow" />
        </div>
        <div class="task-forms" v-if="referFollowTabIndex == 1" v-spin-loading="isLoadingFollow">
          <template v-if="referenceForms.length">
            <div class="task-forms__item" v-for="item in referenceForms">
              <div class="form-title">{{ item.processModel?.formName }}</div>
              <div class="form-render">
                <FormRender ref="formRenderRef" mode="pc" :forms="item.processModel.formItems" :config="{}" v-model="item.data" />
              </div>
            </div>
          </template>
          <a-empty v-else />
        </div>
      </div>
      <!--    end  跟进  -->
    </div>
  </a-drawer>
  <!-- 流程任务待办 end -->

  <!-- 跟进任务待办 start-->
  <a-drawer
    :width="600"
    :visible="isFollowDrawer"
    :header="false"
    :footer="false"
    unmountOnClose
    @close="handelCloseFollowTaskDrawer"
  >
    <div class="handel-container" v-if="isFollowDrawer">
      <div class="followUp-task-container">
        <div class="followUp-header">
          <custom-title title="跟进内容" />
          <icon-close @click="handelCloseFollowTaskDrawer" />
        </div>
        <div class="followUp-logs" v-if="referFollowTabIndex == 0" v-spin-loading="isLoadingFollow">
          <follow-timeline :follow-up-data="followUpData" :is-check-detail="isCheckDetail" @add-follow="handelOpenAddFollow" />
        </div>
      </div>
    </div>
  </a-drawer>
  <!-- 跟进任务待办 end-->

  <!--  操作说明  start -->
  <div class="instructions-container" ref="instructionsContainer" v-show="instructionsVisible">
    <div class="arrow"></div>
    <CustomTitle title="操作说明" isClose @close="handelCloseInstructions" />
    <div class="editor-container" v-html="instructionsText"></div>
  </div>
  <!--  操作说明  end -->

  <!-- 客户跟进 start -->
  <follow-modal
    v-if="isShowFollow"
    v-model="isShowFollow"
    :current-info-param="customerInfoParam"
    @submit-after="handleSubmitFollow"
    @cancel="handleFollowCancel"
  />
  <!--  客户跟进  end-->
  <adjust-plan-time
    v-model="showAdjustTime"
    v-if="showAdjustTime"
    :currentStageTaskId="currentStageTaskId"
    :currentCustomerId="currentCustomerId"
    @adjustTimeSave="getToDoData"
  ></adjust-plan-time>

  <!-- 审批记录 start -->
  <audit-drawer
    v-if="isShowAuditDrawer"
    v-model="isShowAuditDrawer"
    is-audit-log
    :drawer-title="drawerTitle"
    :audit-data="auditData"
  />
  <!-- 审批记录 end -->
</template>

<script setup lang="ts">
import { getCurrentInstance } from "vue";
import dayjs from "dayjs";
import { debounce } from "lodash";
import { Message } from "@arco-design/web-vue";
import FollowTimeline from "./components/followTimeline/index.vue";
import FollowModal from "./components/followModal/index.vue";
import FormRender from "@/components/customComponents/formRender.vue";
import AdjustPlanTime from "./components/AdjustPlanTime/index.vue";
import AuditDrawer from "./components/auditDrawer/index.vue";
import { columns, timeRange, customerInfoParam as customerInfo } from "@/views/home/config";
import type { CurrentInfo } from "@/views/home/types";
import type { numbersType, statusType, ToDoNextTaskRes } from "@/apis/home/type";
import {
  getTodoList,
  getTodoTypeCount,
  clientInfoAndFollow,
  dictDataList,
  toDoNextTask,
  unAssignedCustomerTotal
} from "@/apis/home";
import { previewFormsList } from "@/apis/system/referenceData";
import defaultConfig from "@/config/settings";
import appUrlConfig from "@/config/appUrlconfig";
import { getToken } from "@/utils/auth";
import { mainReceiveData, mainRemoveDataListener, mainSendForceSetData, unmountApp } from "@/microApp/utils";
import { parseOrDefault, disabledDate } from "@/utils";
import { useUserStore } from "@/stores";

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const router = useRouter();

/**
 * 字典跟进类型
 */
const followUpTypes = ref([]);
const getFollowUpType = async () => {
  const { data = [] } = await dictDataList({ dictType: "FOLLER_UP_TYPE" });
  followUpTypes.value = data;
};

/**
 * 当前时段
 */
const timePeriod = ref({
  type: "today",
  timeRange: []
});

/**
 * 流程任务待办
 */
const isHandelDrawer = ref(false);
// 加载表单
const isLoadingForm = ref(false);
// 加载跟进
const isLoadingFollow = ref(false);
const drawerTaskName = ref("");
// 查看详情
const isCheckDetail = ref(false);
// 编辑任务
const isEditTask = ref(false);
// 文件是否正在上传
const isUploadFile = ref(false);
// 上传完成的文件是否获取到url
const isGetUploadFileUrl = ref(false);
// 发送给子应用的数据
const mainSendParams = {
  mainDeptId: userStore.userInfo.mainDeptId,
  homeToDoData: {
    formId: "", // defId
    formInstanceId: "", // instanceId
    commTaskId: ""
  },
  homeToDoFun: "",
  isClick: false,
  isDisabled: false,
  isEdit: false,
  nextTaskList: []
};
/**
 * 参考任务列表
 */
const referenceForms = ref<any[]>([]);
const getPreviewTaskForm = async () => {
  try {
    isLoadingFollow.value = true;
    const { data } = await previewFormsList(customerInfoParam.value.stageTaskId as string);
    referenceForms.value =
      data?.map((item: any) => {
        const formItems = parseOrDefault(item.processModel?.formItems, []).map(item => {
          return {
            ...item,
            props: {
              ...item.props,
              disabled: true
            }
          };
        });
        return {
          processModel: {
            ...item.processModel,
            formItems
          },
          data: item.data ?? {}
        };
      }) || [];
    isLoadingFollow.value = false;
  } catch (err) {
    isLoadingFollow.value = false;
    console.log(err);
  }
};
/**
 * 切换跟进任务和参考任务 tab
 * @desc 仅待办展示参考任务
 */
const referFollowTabIndex = ref(0);
const referFollowTabs = [
  { label: "跟进任务", value: 0 },
  { label: "任务参考", value: 1 }
];
const changeCustomTab = (item: any) => {
  referFollowTabIndex.value = item.value;
  item.value === 0 && getClientInfoAndFollow(customerInfoParam.value.customerId);
  item.value === 1 && getPreviewTaskForm();
};
/**
 * 待办获取指派时间的下个任务
 */
const isLoadingNextTask = ref(false);
const nextTaskList = ref<ToDoNextTaskRes[]>([]);
const isShowNextTask = ref(false);
const getToDoNextTask = async (record: any) => {
  try {
    isLoadingNextTask.value = true;
    const { data } = await toDoNextTask(record.stageTaskId);
    nextTaskList.value = data?.map((item: any) => {
      return {
        ...item,
        plainStartDate: dayjs().format("YYYY-MM-DD")
      };
    });
    isLoadingNextTask.value = false;
  } catch (err) {
    isLoadingNextTask.value = false;
    console.log(err);
  }
};

/**
 * 监听子应用加载
 */
const flowMounted = () => {
  setTimeout(() => {
    isLoadingForm.value = false;
  }, 1000);
};
const flowError = () => {
  isLoadingForm.value = false;
};
/**
 * 流程任务待办
 * @param record
 */
const handelOpenDrawer = async (record: any) => {
  try {
    // 显示弹窗
    isHandelDrawer.value = true;
    // 打开加载
    isLoadingForm.value = true;
    isLoadingFollow.value = true;
    // 操作说明
    instructionsText.value = record.operateRemark;
    drawerTaskName.value = record.taskTitle;
    isCheckDetail.value = false;
    customerInfoParam.value = {
      stageTaskId: record.stageTaskId,
      customerId: record.customerId,
      currentTaskTitle: record.taskTitle,
      currentCommonId: record.commTaskId,
      currentType: record.taskType
    };
    // 传递flow子应用数据
    mainSendParams.homeToDoData = record;
    mainSendParams.isClick = false; // 取消/提交
    mainSendParams.isDisabled = false;
    // 未开始 进行中
    isShowNextTask.value = ["not_start", "ing"].includes(record.taskStatus);
    mainSendForceSetData("form-design-todo", mainSendParams);
    getClientInfoAndFollow(record.customerId);
    isShowNextTask.value && getToDoNextTask(record);
  } catch (err) {
    isLoadingForm.value = false;
    isLoadingFollow.value = false;
    console.log("工作台待办>>>handelOpenDrawer", err);
  }
};
/**
 * 提交流程任务待办
 */
const handelSubmitFormItem = () => {
  mainSendParams.homeToDoFun = "handelSubmit";
  mainSendParams.nextTaskList = nextTaskList.value as any;
  mainSendParams.isClick = true;
  mainSendForceSetData("form-design-todo", mainSendParams);
};
const handelCloseProcessDrawer = () => {
  mainSendParams.homeToDoFun = "handelReset";
  mainSendParams.isClick = true;
  mainSendForceSetData("form-design-todo", mainSendParams);
  closeProcessDrawer();
};
// 关闭流程待办弹窗，初始化参数
const closeProcessDrawer = () => {
  unmountApp("form-design-todo");
  referFollowTabIndex.value = 0;
  instructionsVisible.value = false;
  instructionsText.value = "";
  followUpData.value = [];
  nextTaskList.value = [];
  customerInfoParam.value = {
    ...customerInfo
  };
  getToDoData();
  isHandelDrawer.value = false;
};

/**
 * 跟进任务待办
 */
const isFollowDrawer = ref(false);
const handelOpenProcessDrawer = (record: any) => {
  customerInfoParam.value = {
    stageTaskId: record.stageTaskId,
    customerId: record.customerId,
    currentTaskTitle: record.taskTitle,
    currentCommonId: record.commTaskId,
    currentType: record.taskType
  };
  isFollowDrawer.value = true;
  isCheckDetail.value = false;
  isEditTask.value = false;
  getFollowUpType();
  getClientInfoAndFollow(record.customerId);
};
// 关闭跟进待办弹窗，初始化参数
const handelCloseFollowTaskDrawer = () => {
  isFollowDrawer.value = false;
  followUpData.value = [];
};

/**
 * 查看任务详情
 */
// 跟进任务
const handelFollowTask = (record: any) => {
  isFollowDrawer.value = true;
  getClientInfoAndFollow(record.customerId);
};
// 流程任务
const handelPressTask = async (record: any, isEdit: boolean) => {
  isHandelDrawer.value = true;
  isLoadingForm.value = true;
  instructionsText.value = record.operateRemark;
  drawerTaskName.value = record.taskTitle;
  mainSendParams.homeToDoData = record;
  mainSendParams.isDisabled = !isEdit;
  mainSendParams.isEdit = isEdit;
  mainSendParams.isClick = false;
  mainSendForceSetData("form-design-todo", mainSendParams);
  getClientInfoAndFollow(record.customerId);
};
const handelCheckDetail = (record: any, isEdit: boolean) => {
  try {
    if (isEdit && userStore.userId !== record.userId) {
      return Message.error("非本人操作，无法编辑");
    }
    customerInfoParam.value = {
      stageTaskId: record.stageTaskId,
      customerId: record.customerId,
      currentTaskTitle: record.taskTitle,
      currentCommonId: record.commTaskId,
      currentType: record.taskType
    };
    isCheckDetail.value = !isEdit;
    isEditTask.value = isEdit;
    if (record.taskType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK) {
      handelFollowTask(record);
      return;
    }
    handelPressTask(record, isEdit);
  } catch (err) {
    isLoadingForm.value = false;
    console.log("工作台->>handelCheckDetail", err);
  }
};

/**
 * 添加跟进
 */
const isShowFollow = ref(false);
// 跟进弹窗参数
const customerInfoParam = ref<CurrentInfo>({
  ...customerInfo
});
// 跟进数据
const followUpData = ref([]);
// 打开跟进弹窗
const handelOpenAddFollow = () => {
  isShowFollow.value = true;
};
// 客户跟进详情
const getClientInfoAndFollow = (customerId: string) => {
  isLoadingFollow.value = true;
  clientInfoAndFollow(customerId)
    .then(res => {
      const crmCustomerTrackList = res.data?.crmCustomerTrackList || [];
      followUpData.value = crmCustomerTrackList.map((item: any) => {
        item.roleName = `${item.roleName}  ${item.updateBy}提交于${
          item?.updateTime ? dayjs(item.updateTime).format("HH:mm") : ""
        }`;
        item.date = dayjs(item.trackDatetime).format("YYYY-MM-DD");
        item.time = dayjs(item.trackDatetime).format("HH:mm:ss");
        followUpTypes.value.some((subItem: any) => {
          if (item.trackType === subItem.dictCode) {
            item.trackTypeName = subItem.dictLabel;
            return true;
          }
        });
        return item;
      });
      isLoadingFollow.value = false;
      console.log("跟进详情>>>", res);
    })
    .catch(err => {
      isLoadingFollow.value = false;
      console.log("跟进详情>>>", err);
    });
};
// 跟进提交完成
const handleSubmitFollow = () => {
  const { customerId, currentType } = customerInfoParam.value;
  const isFollowTask = currentType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK;
  if (isFollowTask) {
    isShowFollow.value = false;
    const message = isEditTask.value ? "操作成功" : "任务完成";
    if (isEditTask.value) {
      getClientInfoAndFollow(customerId);
    } else {
      handelCloseFollowTaskDrawer();
    }
    Message.success(message);
    getTimeRange();
  } else {
    getClientInfoAndFollow(customerId);
    Message.success("添加成功");
  }
};
// 关闭提交跟进弹窗
const handleFollowCancel = async () => {
  isShowFollow.value = false;
};

/**
 * 设置时间
 */
const setTime = (start: string, end: string) => {
  params.value.startDate = `${start} 00:00:00`;
  params.value.endDate = `${end} 23:59:59`;
  init();
};
/**
 * 获取当前时段时段类型的开始or结束时间
 */
const weekStartList = [6, 0, 1, 2, 3, 4, 5];
const weekEndList = [0, 6, 5, 4, 3, 2, 1];
const getTimeRange = () => {
  const time = dayjs().format("YYYY-MM-DD");
  switch (timePeriod.value.type) {
    case "today":
      setTime(time, time);
      break;
    case "quarter":
      setTime(dayjs().add(-1, "day").format("YYYY-MM-DD"), time);
      break;
    case "week":
      setTime(
        dayjs().add(-weekStartList[dayjs().day()], "day").format("YYYY-MM-DD"),
        dayjs().add(weekEndList[dayjs().day()], "day").format("YYYY-MM-DD")
      );
      break;
    case "month":
      setTime(dayjs().startOf("month").format("YYYY-MM-DD"), dayjs().endOf("month").format("YYYY-MM-DD"));
      break;
    default:
      break;
  }
};
const setCustomTime = (value: string[]) => {
  params.value.current = 1;
  toDoTable.value = [];
  setTime(value[0], value[1]);
};
/**
 * 切换时段
 */
const changeTime = (itemType: string) => {
  timePeriod.value.type = itemType;
  params.value.current = 1;
  toDoTable.value = [];
  getTimeRange();
};
/**
 * 切换状态
 * @param { statusType } state
 */
const changeTasksState = (state: statusType) => {
  params.value.current = 1;
  params.value.status = state;
  toDoTable.value = [];
  init();
};

/**
 * 待办列表
 */
const isLoadingToDo = ref(false);
const params = ref<any>({
  current: 1,
  size: 10,
  status: "ing",
  startDate: "",
  endDate: "",
  isMy: true,
  searchType: 2
});
const numbers = ref<numbersType>({
  allNumber: 0,
  notStartNumber: 0,
  ingNumber: 0,
  completedNumber: 0,
  normalNumber: 0,
  postponeNotStartNumber: 0,
  notCompleteNumber: 0,
  auditNumber: 0,
  failNumber: 0
});
const toDoTable = ref([]);
const total = ref(0);
const getToDoData = async () => {
  try {
    isLoadingToDo.value = true;
    const { data } = await getTodoList(params.value);
    const list = data?.list || [];
    toDoTable.value = list.map((item: any) => {
      return {
        ...item,
        plainStartDate: item.plainStartDate ? dayjs(item.plainStartDate).format("YYYY-MM-DD") : "",
        factStartDate: item.factStartDate ? dayjs(item.factStartDate).format("YYYY-MM-DD") : "",
        plainEndDate: item.plainEndDate ? dayjs(item.plainEndDate).format("YYYY-MM-DD") : "",
        factEndDate: item.factEndDate ? dayjs(item.factEndDate).format("YYYY-MM-DD") : "",
        isOut: item.isOut === 1 ? "是" : "否",
        postponeStatus: ["not_complete", "postpone_not_start"].includes(item.postponeStatus) ? "异常" : "正常"
      };
    });
    total.value = data?.total || 0;
    isLoadingToDo.value = false;
  } catch (err) {
    console.log(err);
    isLoadingToDo.value = false;
  }
};
const handleCheckMyTask = (e: any) => {
  params.value.isMy = !e;
  init();
};
const getToDoStatusCount = async () => {
  const { status, startDate, endDate, isMy, searchType, value } = params.value;
  const numberRes = await getTodoTypeCount({ status, startDate, endDate, isMy, searchType, value });
  numbers.value = numberRes.data;
};
const init = async () => {
  getToDoData();
  getToDoStatusCount();
};
const handleChangePagination = async (val: number) => {
  params.value.current = val;
  getToDoData();
};
const handleChangeSizePagination = (val: number) => {
  params.value.size = val;
  getToDoData();
};

/**
 * 操作说明
 * todo:可封装hook
 */
const instructionsVisible = ref(false);
const instructionsLeft = ref("0px");
const instructionsTop = ref("40px");
const arrowLeft = ref("0px");
const arrowTop = ref("40px");
const instructionsWidth = ref(400);
const instructionsText = ref("");
const openInstructions = async () => {
  instructionsVisible.value = true;
  await nextTick();
  const instructionsTitleEl = proxy.$refs.instructionsTitle;
  const instructionsTitleRect = instructionsTitleEl.getBoundingClientRect();
  instructionsLeft.value = `${instructionsTitleRect.left - instructionsWidth.value - 40}px`;
  instructionsTop.value = `${instructionsTitleRect.top}px`;
  arrowLeft.value = `${instructionsTitleRect.left - 41}px`;
  arrowTop.value = `${instructionsTitleRect.top + 10}px`;
};
const handelCloseInstructions = () => {
  window.removeEventListener("resize", handleResize);
  instructionsText.value = "";
  instructionsVisible.value = false;
};
let initialInstructionsWidth: any = 0;
const handleResize = debounce(() => {
  const instructionsTitleEl = proxy.$refs.instructionsTitle;
  if (!instructionsTitleEl) return;
  const instructionsTitleRect = instructionsTitleEl.getBoundingClientRect();
  // 获取初始宽度，确保在首次渲染后进行
  if (!initialInstructionsWidth) {
    initialInstructionsWidth = instructionsWidth.value;
  }
  instructionsLeft.value = `${instructionsTitleRect.left - initialInstructionsWidth - 40}px`;
  instructionsTop.value = `${instructionsTitleRect.top}px`;
  arrowLeft.value = `${instructionsTitleRect.left - 41}px`;
  arrowTop.value = `${instructionsTitleRect.top + 10}px`;
}, 10);

/**
 * 调整计划
 */
const currentStageTaskId = ref("");
const currentCustomerId = ref("");
const showAdjustTime = ref(false);
const handleAdjustTime = (row: any) => {
  currentStageTaskId.value = row.stageTaskId;
  currentCustomerId.value = row.customerId;
  showAdjustTime.value = true;
};

/**
 * 子应用回传数据
 * @param data
 */
const getChildData = (data: any) => {
  isUploadFile.value = data.isUploadFile;
  isGetUploadFileUrl.value = data.isGetUploadFileUrl;
  // 关闭弹窗刷新数据
  if (data.isOptionsDrawer) {
    data.isRefresh && getTimeRange();
    closeProcessDrawer();
  }
};

//跳转到客户详情
const toCustomerInfo = (customerId: string) => {
  const linkUrl = `/crm/client-info?customerId=${customerId}&closBrowser=1`;
  window.open(linkUrl);
};

//待分配数量统计
//type:1 营销   2工程
const unAssignedInfo = ref({ num: 0, type: 1 });
const getUnAssignedInfo = async () => {
  const { data } = await unAssignedCustomerTotal();
  unAssignedInfo.value = data ?? { num: 0, type: 1 };
};
const toUnassignList = () => {
  const type = unAssignedInfo.value.type;
  if (type == 1) {
    router.push({ path: "/client-manager", query: { unAssigned: 1 } });
  } else {
    unmountApp("projectmanage");
    router.push({ path: "/projectmanage", query: { unAssigned: 1 } });
  }
};

/**
 * 审批
 */
const isShowAuditDrawer = ref(false);
const auditData = ref({});
const drawerTitle = ref("");
const handelAudit = (data: any) => {
  isShowAuditDrawer.value = true;
  auditData.value = data;
  drawerTitle.value = data.taskTitle;
};

onMounted(() => {
  getTimeRange();
  getFollowUpType();
  getUnAssignedInfo();
  // ToDo：封装
  mainReceiveData("form-design-todo", getChildData);
  window.addEventListener("resize", handleResize);
});
onUnmounted(() => {
  mainRemoveDataListener("form-design-todo", getChildData);
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped lang="scss">
@import "../index";
.pending-tasks {
  @include flex;
  flex-direction: column;
  flex: 1;
  overflow-y: auto;
  background-color: #fff;
  box-shadow: 4px 5px 16px 0 rgba(4, 19, 74, 0.04);
  border-radius: 10px;
  &_total {
    display: flex;
    align-items: center;
    .unassgin-total {
      background: url("@/assets/images/unAssignBg.png") no-repeat;
      background-size: 100% 100%;
      padding: 5px 20px;
      margin-left: 10px;
      font-size: 12px;
      color: #fff;
      cursor: pointer;
    }
  }
  &_header {
    @include flex-between;
    flex-wrap: wrap;
    padding-bottom: 12px;
    border-bottom: 1px solid rgba(194, 212, 232, 0.502);
    .pending-tasks_filter {
      @include flex-align;
    }

    .custom-tabs {
      margin-right: 11px;
    }
  }

  &_state {
    .overdue {
      :deep(.arco-radio-label) {
        color: #ff3333;
      }
    }
  }

  // 只看自己
  &_self {
    padding: 12px 20px;
    box-sizing: border-box;
    border: 1px solid #e1e6ed;
    border-bottom: 0;

    .custom-checkbox-card {
      padding: 10px 16px;
      border: 1px solid var(--color-border-2);
      border-radius: 4px;
      width: 250px;
      box-sizing: border-box;
    }

    .custom-checkbox-card-mask {
      height: 14px;
      width: 14px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      border: 1px solid var(--color-border-2);
      box-sizing: border-box;
    }

    .custom-checkbox-card-mask-dot {
      width: 8px;
      height: 8px;
      border-radius: 50%;
    }

    .custom-checkbox-card-title {
      font-size: 14px;
      color: rgba(0, 0, 0, 0.9);
    }

    .custom-checkbox-card:hover,
    .custom-checkbox-card-checked {
      border-color: rgb(var(--primary-6));
    }

    .custom-checkbox-card-checked .custom-checkbox-card-mask {
      border-color: rgb(var(--primary-6));
    }

    .custom-checkbox-card-checked .custom-checkbox-card-mask-dot {
      background-color: rgb(var(--primary-6));
    }
  }

  :deep(.arco-table) {
    flex: 1;
    overflow-y: auto;
  }
}

.form-container,
.followUp-container {
  height: 100%;
  width: 50%;
}

// 跟进任务
.handel-container {
  @include flex;
  height: 100%;

  .form-container {
    padding-right: 16px;
    border-right: 1px solid #dcdfe6;
    position: relative;

    .opt-instructions {
      margin: 24px 0 4px;
      font-size: 12px;
      color: #007dff;
      line-height: 22px;
      cursor: pointer;
    }

    .form-items {
      height: 60vh;
      overflow-y: auto;
      padding: 10px;
      box-sizing: border-box;
      background-color: #f6f8fa;
      border: 1px solid #dcdfe6;

      .micro-app,
      :deep(micro-app-body) {
        min-width: 100% !important;
      }
    }

    .form-btns {
      position: absolute;
      bottom: 0;

      ::v-deep(.arco-btn) {
        margin-right: 10px;
      }
    }
  }

  .followUp-container,
  .followUp-task-container {
    @include flex-column;
    height: 100%;
    padding-left: 16px;
    .followUp-header {
      @include flex-between;
      align-items: center;
      margin-bottom: 24px;

      :deep(.title) {
        margin-bottom: 0;
      }

      svg {
        font-size: 17px;
        cursor: pointer;
      }
    }
    .title {
      font-size: 16px;
      margin-bottom: 16px;
    }
  }
}
.followUp-task-container {
  width: 100%;
}

.followUp-top {
  @include flex-between;
  margin-bottom: 20px;
  :deep(.arco-icon) {
    cursor: pointer;
  }
}
.followUp-logs {
  flex: 1;
  overflow-y: auto;
}
// 参考任务
.task-forms {
  position: relative;
  flex: 1;
  overflow-y: auto;
  :deep(.arco-empty) {
    @include position-center;
  }
  &__item {
    .form-title {
      margin-bottom: 5px;
      font-size: 14px;
      color: #3d3d3d;
      line-height: 22px;
    }
    .form-render {
      padding: 10px;
      background: #f6f8fa;
      border: 1px solid #dcdfe6;
    }
    & + .task-forms__item {
      margin-top: 20px;
    }
  }
}
// 操作说明
.instructions-container {
  @include flex;
  flex-direction: column;
  width: 400px;
  height: 90vh;
  overflow: auto;
  position: fixed;
  left: v-bind(instructionsLeft);
  top: v-bind(instructionsTop);
  z-index: 9999;
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-sizing: border-box;

  .arrow {
    position: fixed;
    left: v-bind(arrowLeft);
    top: v-bind(arrowTop);
    z-index: 9999;
    width: 0;
    height: 0;
    border: 14px solid transparent;
    border-left: 14px solid #fff;
  }

  .editor-container {
    flex: 1;
    width: 100%;
    overflow: auto;
  }
}

// 表格样式
:deep(.arco-table-header) th {
  background-color: #f2f6fc !important;
}

:deep(.arco-table-body) tr:nth-child(2n) td {
  background-color: #f5f7fa !important;
}

:deep(
    .arco-table-stripe:not(.arco-table-dragging)
      .arco-table-tr:not(.arco-table-tr-empty):not(.arco-table-tr-summary):nth-child(even)
      .arco-table-td.arco-table-col-fixed-right::before
  ) {
  background-color: #f5f7fa !important;
}

// 调整计划
.delay-days {
  @include flex-column;
  width: 100%;
  &-date {
    display: inline-flex;
    align-items: center;
    height: 32px;
    margin: 4px 0;
    padding: 5px 12px;
    box-sizing: border-box;
    border-radius: 2px 2px 2px 2px;
    border: 1px solid #f2f3f5;
    font-size: 14px;
    line-height: 22px;
  }
  &-tip {
    font-size: 12px;
    color: #86909c;
    line-height: 22px;
  }
}
.next-task {
  margin-top: 20px;
  height: 20vh;
  overflow: scroll;
  &-title {
    font-size: 16px;
    color: #86909c;
    margin-bottom: 10px;
  }
}

.customer-link {
  color: #007aff;
  cursor: pointer;
}
</style>
